<template>
  <div class="order-management">
    <el-card>
      <!-- 操作栏 -->
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="订单编号">
          <el-input v-model="searchForm.id" placeholder="请输入订单编号"></el-input>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.orderStatus" placeholder="全部">
            <el-option label="全部" value=""></el-option>
            <el-option label="待提交" value="待提交"></el-option>
            <el-option label="待审核" value="待审核"></el-option>
            <el-option label="待收货" value="待收货"></el-option>
            <el-option label="待入库" value="待入库"></el-option>
            <el-option label="订单关闭" value="订单关闭"></el-option>
            <el-option label="待结算" value="待结算"></el-option>
            <el-option label="已完成" value="已完成"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="供应商名称">
          <el-input v-model="searchForm.supplier" placeholder="请输入供应商名称"></el-input>
        </el-form-item>
        <el-form-item label="采购仓库">
          <el-select v-model="searchForm.warehouse" placeholder="请选择">
            <el-option label="全部" value=""></el-option>
            <el-option
              v-for="item in warehouseOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单创建时间">
          <el-date-picker
            v-model="searchForm.createTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleDeleteBatch">批量删除</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"  @click="uploadExcelDialog=true">导入</el-button>
          <el-button type="primary"  @click="downloadExcel">导出</el-button>
        </el-form-item>
      </el-form>
    </el-card>


      <!-- 数据展示层 -->
      <el-table :data="tableData" border
                style="width: 100%"
      @selection-change="handleSelectionChange"
                @row-click="handleEdit">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="采购订单号" />
        <el-table-column prop="goodName" label="商品名称" />
        <el-table-column prop="goodImageUrl" label="商品图片" >
          <template slot-scope="scope">
            <img :src="scope.row.goodImageUrl" alt="商品图片" style="max-width: 100%; max-height: 200px;" />
          </template>
        </el-table-column>
        <el-table-column prop="supplier" label="采购供应商" />
        <el-table-column prop="warehouse" label="采购仓库" />
        <el-table-column prop="quantity" label="采购量" />
        <el-table-column prop="unitPrice" label="采购单价(元)" />
        <el-table-column prop="taxAmount" label="含税金额(元)" />
        <el-table-column prop="deliveryDate" label="要货日期" />
        <el-table-column prop="orderStatus" label="订单状态">
          <template slot-scope="scope">
            <el-tag
              :type="getOrderStatusTagType(scope.row.orderStatus)"
              size="small"
            >{{ scope.row.orderStatus }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.orderStatus === '待审核'"
              size="mini"
              type="success"
              @click.stop="openAuditDialog(scope.row)"
            >审核</el-button>
          </template>
        </el-table-column>
      </el-table>

    <!--      新增/修改表单-->
    <el-dialog :title= this.title :visible.sync="dialogVisible" width="60%">
      <el-form :model="Editform"  ref="purchaseForm" :rules="rules" label-width="100px">
        <!-- 第一行：采购供应商和采购仓库并列 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="采购供应商" prop="supplier">
              <el-select v-model="Editform.supplier" placeholder="请选择供应商" style="width: 100%;">
                <el-option
                  v-for="item in supplierOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购仓库" prop="warehouse">
              <el-select v-model="Editform.warehouse" placeholder="请选择仓库" style="width: 100%;">
                <el-option
                  v-for="item in warehouseOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第二行：采购量和添加商品按钮并列 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="采购量" prop="quantity">
              <el-input v-model="Editform.quantity" placeholder="请输入数量" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label=" ">
              <el-button type="primary" @click="showAddGoodDialog">添加商品</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第三行：含税合计单独一列 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="含税合计（元）">
              <el-input v-model="Editform.taxAmount" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第四行：要货日和订单状态并列 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="要货日" prop="deliveryDate">
              <el-date-picker
                v-model="Editform.deliveryDate"
                type="date"
                placeholder="请选择日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"            style="width: 100%;"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单状态" v-if="this.title === '修改' ? true : false">
              <el-select v-model="Editform.orderStatus" placeholder="全部" clearable style="width: 100%;">
                <el-option
                  v-for="status in orderStatusOptions"
                  :key="status.value"
                  :label="status.label"
                  :value="status.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第五行：备注单独一列 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input type="textarea" v-model="Editform.remark" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 展示已添加的商品信息 -->
        <el-card v-if="Editform.goodName && Editform.goodName.trim() !== ''">
          <el-form-item label="商品名称">
            <el-input type="textarea" v-model="Editform.goodName" disabled></el-input>
          </el-form-item>
          <el-form-item label="商品图片">
            <img :src="uploadedImagePreview || require('@/assets/images/default.png')" alt="预览图" style="max-width: 100%; max-height: 200px;" />
          </el-form-item>
          <el-form-item label="商品单价">
            <el-input type="textarea" v-model="Editform.unitPrice" disabled></el-input>
          </el-form-item>
        </el-card>

      </el-form>

      <el-row :gutter="20">
        <el-col :span="24" style="text-align: right;">
          <el-button @click="dialogVisible = false">关 闭</el-button>
          <el-button type="primary" @click="onSubmit">确 定</el-button>
        </el-col>
      </el-row>
    </el-dialog>

    <!-- 添加商品对话框 -->
    <el-dialog title="添加商品" :visible.sync="addGoodDialogVisible" width="40%">
      <el-form :model="Editform" label-width="100px"> <!-- 使用临时对象 tempGoodForm -->
        <el-form-item label="商品名称">
          <el-input v-model="Editform.goodName" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item label="商品图片" prop="goodImageUrl">
          <el-upload
            class="upload-demo"
            drag
            action=""
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleChange"
            :limit="1">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <!-- 预览图 -->
          </el-upload>
          <div v-if="uploadedImagePreview">
            <img :src="uploadedImagePreview" alt="预览图" style="max-width: 100%; max-height: 200px;" />
          </div>
        </el-form-item>
        <el-form-item label="商品单价">
          <el-input v-model="Editform.unitPrice" placeholder="请输入商品单价"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addGoodDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAddGood">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 审核弹窗 -->
    <el-dialog title="订单审核" :visible.sync="auditDialogVisible" width="40%">
      <el-form :model="auditForm" label-width="100px">
        <el-form-item label="审核结果">
          <el-radio-group v-model="auditForm.auditResult">
            <el-radio label="待审核"></el-radio>
            <el-radio label="审核通过"></el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="审核理由" v-if="auditForm.auditResult === '审核通过'">
          <el-input v-model="auditForm.auditReason" type="textarea" :rows="3" placeholder="请输入审核理由"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="auditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAudit">提 交</el-button>
      </span>
    </el-dialog>

    <!-- 文件上传弹窗 -->
    <el-dialog title="上传文件" :visible.sync="uploadExcelDialog" width="30%">
      <!--上传组件-->
      <el-upload
        class="upload-demo"
        drag
        action=""
        :before-upload="beforeUpload"
        :file-list="fileList"
        :http-request="uploadExcelFun"
        :on-change="handleFileChange"
      >
        <i class="el-icon-upload"></i>

        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>

      </el-upload>

      <div slot="footer" class="dialog-footer">
        <el-button @click="uploadExcelDialog = false">取 消</el-button>

        <el-button type="primary" @click="">确 定</el-button>

      </div>
    </el-dialog>
    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 15]"
      :page-size="queryPage.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      prev-text="上一页"
      next-text="下一页"
    />



  </div>
</template>

<script>
import {
  addOrderPurchase,
  deleteOrderPurchase,
  findAllByPage, findAllSupplierName,
  findAllWarehouseName,
  updateOrderPurchase,
  uploadExcel
} from '@/api/order/orderPurchase'
import { uploadPicture } from '@/api/upload'

export default {
  name: 'orderPurchase',
  data() {
    return {
      uploadExcelDialog:false,
      file: null,
      fileList: [],
      auditDialogVisible: false, // 控制审核弹窗显示
      auditForm: {
        auditResult: '待审核', // 审核结果，默认是待审核
        auditReason: ''        // 审核理由
      },
      currentRow: null,         // 当前正在审核的数据行
      uploadedImageFile: null, // 存储原始文件对象
      uploadedImagePreview: null, // 存储本地预览地址
      supplierOptions:[],
      warehouseOptions:[],
      rules: {
        supplier: [
          { required: true, message: '采购供应商不能为空', trigger: 'blur' }
        ],
        warehouse: [
          { required: true, message: '采购仓库不能为空', trigger: 'change' }
        ],
        deliveryDate: [
          { required: true, message: '要货日期不能为空', trigger: 'change' }
        ],
        orderStatus: [
          { required: true, message: '订单状态不能为空', trigger: 'change' }
        ]
      },
      addGoodDialogVisible:false,
      orderStatusOptions: [
        { value: '待审核', label: '待审核' },
        { value: '待收货', label: '待收货' },
        { value: '待入库', label: '待入库' },
        { value: '待结算', label: '待结算' },
        { value: '订单关闭', label: '订单关闭' },
        { value: '已完成', label: '已完成' },
      ],
      //复选框
      multipleSelection:[],
      title:'',
      dialogVisible:false,
      Editform: {
        supplier: '',
        warehouse: '',
        quantity: '',
        unitPrice: '',
        taxAmount: '', // 税后金额
        orderStatus: '',
        deliveryDate: '',
        goodName:'',
        goodImageUrl:'',
        remark: ''
      },
      // 搜索栏
      searchForm:{
      },
      queryPage:{
        pageNum: 1,
        pageSize: 5
      },
      tableData: [],
      currentPage: 1,
      pageNum: 1,
      pageSize: 10,
      total: 0,
    }
  },
  created() {
    this.loadData();
  },

  methods: {
    downloadExcel(){
      this.$confirm(`确定要下载Excel吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        window.location.href="http://localhost:8888/order/purchase/download/excel"
        this.$message({
          message: '下载成功!',
          type: 'success',
          duration: 1200
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消下载'
        });
      });
    },
    beforeUpload(){
      console.log('开始上传，清空上次的文件列表');
      this.fileList = []; // 清空文件列表
      return true;
    },
    uploadExcelFun() {
      const file = this.file;
      const formData = new FormData();
      formData.append('file', file);
      //封装文件上传的方法
      uploadExcel(formData).then(res => {
        if (res.code === 20000) {
          this.$message.success('上传成功');
          //上传成功后添加到文件列表
          this.fileList.push({
            name: file.name,
          });
          this.uploadExcelDialog = false;
          this.pageNum = 1;
          this.loadData()
        } else {
          this.$message.error(res.message || '上传失败');
        }
      })
    },
    handleFileChange(file) {
      this.file = file.raw;
    },
    submitAudit() {
      const { auditResult, auditReason } = this.auditForm;
      if (auditResult === '审核通过' && !auditReason.trim()) {
        this.$message.warning('请填写审核理由');
        return;
      }
      // 构造更新后的订单对象
      const updatedOrder = {
        ...this.currentRow,
        orderStatus: auditResult === '审核通过' ? '已完成' : this.currentRow.orderStatus,
        auditReason: auditReason
      };
      // 调用 API 更新订单状态
      updateOrderPurchase(updatedOrder).then(res => {
        if (res.code === 20000) {
          this.$message.success('审核提交成功');
          this.auditDialogVisible = false;
          this.loadData(); // 刷新表格数据
        } else {
          this.$message.error(res.message || '审核失败');
        }
      }).catch(() => {
        this.$message.error('网络异常，请重试');
      });
    },
    openAuditDialog(row) {
      this.currentRow = { ...row }; // 复制当前行数据
      this.auditForm = {
        auditResult: '待审核',
        auditReason: ''
      };
      this.auditDialogVisible = true;
    },
    getOrderStatusTagType(status) {
      switch (status) {
        case '待审核':
        case '待收货':
        case '待入库':
        case '待结算':
          return 'warning'; // 黄色 tag
        case '订单关闭':
          return 'info'; // 灰色 tag
        case '已完成':
          return 'success'; // 绿色 tag
        default:
          return '';
      }
    },
    handleChange(file) {
      const rawFile = file.raw;
      if (!rawFile) return;
      // 只允许一个文件
      this.uploadedImageFile = rawFile;
      // 创建本地预览地址
      const previewUrl = URL.createObjectURL(rawFile);
      this.uploadedImagePreview = previewUrl;
    },
    confirmAddGood(){
      // 关闭添加商品对话框
      this.addGoodDialogVisible = false;
    },
    showAddGoodDialog(){
      this.addGoodDialogVisible = true
    },
    // 批量删除
    handleDeleteBatch() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请至少选择一条数据')
        return
      }
      this.$confirm('此操作将永久删除选中的文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        // distinguishCancelAndClose: true,    // 重要，设置为true才会把右上角X和取消区分开来
        // closeOnClickModal: false
      }).then(() => {// 用户点击确定进入此流程
        const ids = this.multipleSelection.join(',')
        deleteOrderPurchase(ids)
          .then(ret => {
            if (ret.code === 20000) {
              this.$message.success('批量删除成功')
              this.queryPage.pageNum = 1
              this.loadData()
            }else{
              this.$message.error(ret.message || '删除失败')
            }
          })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    //select方法监控
    handleSelectionChange(val){
      this.multipleSelection = val.map(item => item.id)
    },
    // 新增/修改表单的提交
    onSubmit(){
      this.$refs.purchaseForm.validate(valid => {
          if (valid) {
            if (this.uploadedImageFile) {
              const formData = new FormData();
              formData.append("file", this.uploadedImageFile);
              uploadPicture(formData).then(res => {
                console.log("res",res)
                if (res.code === 20000) {
                  this.Editform.goodImageUrl = res.data; // 假设接口返回的图片路径是 res.data.url
                  this.submitOrderForm(); // 提交订单数据
                } else {
                  this.$message.error('图片上传失败');
                }
              }).catch(() => {
                this.$message.error('图片上传出错');
              });
            } else {
              this.submitOrderForm(); // 没有图片直接提交表单
            }
          }
          else {
            this.$message.error('请正确填写表单')
            return false
          }
        })
    },
    submitOrderForm() {
      // 表单校验通过，执行新增或修改逻辑
      if (this.title === '新增') {
        console.log('新增')
        console.log("this.editform",this.Editform)
        addOrderPurchase(this.Editform).then(res => {
          if (res.code == 20000) {
            this.$message.success('添加成功！');
            this.dialogVisible = false;
            this.loadData();
          } else {
            this.$message.error('添加失败！');
          }
        })
      }
      if (this.title === '修改') {
        console.log('修改')
        updateOrderPurchase(this.Editform).then(res => {
          if (res.code == 20000) {
            this.$message.success('修改成功！');
            this.dialogVisible = false;
            this.loadData();
          } else {
            this.$message.error('修改失败！');
          }
        })
      }
    },

    //分页-页码大小改变
    handleSizeChange(newSize) {
      this.queryPage.pageSize = newSize
      this.loadData()
    },
    //分页-当前页码数改变
    handleCurrentChange(page){
      this.queryPage.pageNum = page;
      this.loadData();
    },
    // 加载数据
    loadData(){
      findAllByPage(this.queryPage).then(res=>{
        if(res.code == 20000){
          this.total = res.data.total
          this.tableData = res.data.list.map(item => ({
            ...item,
            goodImageUrl: `https://jinghaiyang.oss-cn-beijing.aliyuncs.com/app/upload/${item.goodImageUrl}`
          }))
        }else{
          this.$message.error(res.message);
        }
      })
      findAllWarehouseName().then(res=>{
        if(res.code == 20000){
          this.warehouseOptions = res.data.map(item => ({
            label: item,
            value: item
          }));
        }else{
          this.$message.error(res.message);
        }
      })
      findAllSupplierName().then(res=>{
        if(res.code == 20000){
          this.supplierOptions = res.data.map(item => ({
            label: item,
            value: item
          }));
        }else{
          this.$message.error(res.message);
        }
      })
    },
    //查询
    handleSearch(){
      // 构建查询参数
      const params = { ...this.searchForm,
        createTime: undefined };

      // 重置分页
      this.queryPage.pageNum = 1;
      this.queryPage.pageSize = 5;

      // 处理时间范围
      if (this.searchForm.createTime?.length === 2) {
        params.startDate = this.searchForm.createTime[0];
        params.endDate = this.searchForm.createTime[1];
      }
      // 合并查询参数和分页参数
      this.queryPage = { ...this.queryPage, ...params};

      // 加载数据
      this.loadData();
    },
    //重置
    handleReset(){
      this.searchForm = {};
      this.queryPage = {};
      this.queryPage.pageNum = 1;
      this.queryPage.pageSize = 5;
      this.Editform = {}
      this.loadData();
    },
    handleAdd(){
      this.title = '新增'
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.title = '修改';
      this.dialogVisible = true;
      this.Editform =  { ...row };
      // 初始化上传预览图
      if (row.goodImageUrl) {
        this.uploadedImagePreview = row.goodImageUrl; // 显示原图
      } else {
        this.uploadedImagePreview = null;
      }

    },
    // 计算税金
    calculateTaxAmount() {
      const { quantity, unitPrice } = this.Editform;
      if (!quantity || !unitPrice) {
        this.Editform.taxAmount = '';
        return;
      }
      let subtotal = parseFloat(quantity) * parseFloat(unitPrice);
      if (subtotal < 2000) {
        this.Editform.taxAmount = subtotal.toFixed(2);
      } else {
        const taxableAmount = subtotal - 2000;
        const tax = taxableAmount * 0.015;
        this.Editform.taxAmount = (subtotal + tax).toFixed(2);
      }
    },
  },
  watch: {
    'Editform.quantity': function(newVal) {
      this.calculateTaxAmount();
    },
    'Editform.unitPrice': function(newVal) {
      this.calculateTaxAmount();
    }
  },
}
</script>


<style scoped lang="scss">
.order-management {
  padding: 20px；
}
</style>
